package com.hongtu.supplychain.finance.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.hongtu.supplychain.finance.consumer.controller.client.UserClient;
import com.hongtu.supplychain.finance.consumer.params.enums.EAppBackCode;
import com.hongtu.supplychain.finance.consumer.replyata.ReplyData;
import com.hongtu.supplychain.finance.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 手机拦截器
 */
public class MAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisPlugin jedisPlugin;

    @Autowired
    private UserClient userClient;

    public static List<String> excludeUrl = new ArrayList<String>(){{

    }};

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getHeader(MUtil.PUBLIC_LB) == null){  //WebChat
            return true;
        }

        String requestUrl   = request.getRequestURI();
        String ticket       = request.getHeader(MUtil.MOBILE_TICKET);

        if(ticket != null){
            String value = null;
            if((value = jedisPlugin.get(String.format(MUtil.MOBILE_TICKET_FORREDIS, ticket))) != null){
                UserLoginInfo userInfo = JSONObject.parseObject(value, UserLoginInfo.class);
                SessionThreadLocal.setSession(userInfo);
            }else{                          //解密ticket 模拟登录
                simulateLogin(ticket);
            }
            return true;
        }else if(excludeUrl.contains(requestUrl)){
            return true;
        }else{
            loginTimeout(response, EAppBackCode.RE_LOGIN);
            return false;
        }
    }

    private void loginTimeout(HttpServletResponse httpServletResponse, EAppBackCode backCode) {
        try {
            ReplyData replyData = new ReplyData();
            replyData.setCode(backCode.getCode());
            replyData.setMsg(backCode.getTypeName());
            httpServletResponse.setContentType("text/html; charset=UTF-8");
            httpServletResponse.getWriter().print(JSONObject.toJSONString(replyData));
            httpServletResponse.getWriter().close();
        } catch (Exception e) {

        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 手机模拟登录
    private void simulateLogin(String mobileTicket) throws Exception {
        String userIdString = AESUtil.decrypt(MUtil.MOBILE_TICKET_PASSWORD, Constants.LOGINUSER_MOBILETICKET_VECTOR, mobileTicket);
        Integer userId = Integer.parseInt(userIdString);

        UserLoginInfo userInfo = userClient.getUserInfoById(userId);

        SessionThreadLocal.setSession(userInfo);

        jedisPlugin.set(String.format(MUtil.MOBILE_TICKET,mobileTicket),JSONObject.toJSONString(userInfo));
    }
}
